package core;

import fileoperation.FileDeletion;
import Index.index;
import repository.Repository;

import java.io.File;

    public static void Rm(String filename) throws Exception {
        File file = new File(Repository.getWorkTree() + File.separator + filename);
        // 检查文件是否在暂存区
        if (!file.exists()) {
            System.out.println("该文件不存在，请检查后再试！");
        } else if (file.isDirectory()) {
            // 若为文件夹，则需添加命令参数 -r
            System.out.println("使用命令参数-r来递归移除文件夹\n");
        } else {
            String relativePath = index.getRelativePath(file);
            index.indexOffile();
            // 若在暂存区，则删除
            if (index.getHashMap().containsKey(relativePath)) {
                index.deleteFromIndex(file);
                FileDeletion.deleteFile(file);
                System.out.println("rm " + filename);
            } else {
                // 若不在暂存区，则提示
                System.out.println(filename + "\" 不存在，请检查后再尝试\"");
            }
        }
    }

    public static void RMr(String filePath) throws Exception {
        //递归删除，进入某个目录，删除该目录下所有文件和子目录
        File file = new File(Repository.getWorkTree() + File.separator + filePath);
        if ((!file.exists())) {
            System.out.println("No such file exists!");
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                RMr(index.getRelativePath(files[i]));
            }
            file.delete();
            System.out.println("rm " + index.getRelativePath(file));
        } else {
            Rm(index.getRelativePath(file));
        }
    }
}